/**
 * Created by ziyu on 17/3/7.
 */
import React, {Component, PropTypes} from 'react'
import moment from 'moment'
import Styles from './Index.less'
import SearchStyle from '../../../common/less/search.less'
import {message, Col, Icon, Select, Spin} from 'antd'
import {fetchPost} from '../../../../utils/request'
import List from './List'
import Search from '../../../common/components/Search'
import Detail from './detail/Detail'
import $ from 'jquery'

const Option = Select.Option

class Index extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      isNewAdd: props.isNewAdd,
      processNode: props.processNode,
      isReupload: props.isReupload,
      stageStatus: props.stageStatus,
      userId: null,
      tradeNo: null,
      extraStatus: null,
      photoReUploadTime: null,
      photoReUploadAllow: null,
      mobileRedialAllow: null,
      getListApi: props.getListApi,
      id: null,
      refresh: false,
      processingCount: null,
      stepType: props.stepType,
      list: [],
      auditorWorkTime: {},
      userWaitTime: {},
      item: {},
      isFetch: false,
      showList: 'show',
      page: {
        currentPage: 1,
        pageSize: 13,
        totalCount: 0
      },
      params: {
        isShowAll: '',
        findtype: '',
        duration: '',
        realCapital: '',
        inputValue: '',
        startDate: moment().subtract('days', 60).format('YYYY-MM-DD'),
        endDate: moment().add('days', 30).format('YYYY-MM-DD'),
      },
      activeKey: 'detail',
      searchParams: {
        list: [],
        api: '/common/query'
      },
      searchParamsList0: [
        {
          name: 'Order Created Date',
          type: 'range',
          key: ['startDate', 'endDate'],
          className: 'pr20',
          placeHolder: '',
          values: [
            moment().subtract('days', 60),
            moment().add('days', 30)
          ]
        },
        {
          name: '',
          type: 'buttonRadio',
          key: 'trafficType',
          className: 'pr20',
          values: [
            {
              value: '',
              name: 'All'
            },
            {
              value: 'promotion',
              name: 'Promotion'
            },
            {
              value: 'nature',
              name: 'Organic'
            }
          ],
        },
        {
          name: '',
          type: 'buttonRadio',
          key: 'isShowAll',
          className: 'pr20',
          values: [
            {
              value: '',
              name: 'My Order',
            },
            {
              value: '1',
              name: 'All Order',
            }
          ],
        },
        {
          name: 'Channel',
          type: 'newSelect',
          key: 'channelCode',
          className: 'pr20',
          values: []
        },
        {
          name: 'Re-upload status',
          type: 'select',
          key: 'isReupload',
          className: 'pr200',
          values: [
            {
              value: '9',
              name: 'Re-upload completed',
            },
            {
              value: '1',
              name: 'Waiting for reupload',
            }
          ]
        }, {
          name: 'Auditor',
          type: 'select',
          key: 'auditor',
          className: 'pr20',
          values: [{value: '', name: 'All'}]
        },
        {
          name: 'Filter',
          type: 'group',
          key: ['findtype', 'inputValue'],
          className: 'pr20',
          values: [{value: '', name: 'Please Select'}]
        },
        {
          name: '',
          type: 'search',
          key: '',
          className: 'pr20',
          values: []
        }
      ],
      searchParamsList1: [
        {
          name: 'Order Created Date',
          type: 'range',
          key: ['startDate', 'endDate'],
          className: 'pr20',
          placeHolder: '',
          values: [
            moment().subtract('days', 60),
            moment().add('days', 30)
          ]
        },
        {
          name: '',
          type: 'buttonRadio',
          key: 'trafficType',
          className: 'pr20',
          values: [
            {
              value: '',
              name: 'All'
            },
            {
              value: 'promotion',
              name: 'Promotion'
            },
            {
              value: 'nature',
              name: 'Organic'
            }
          ],
        },
        {
          name: '',
          type: 'buttonRadio',
          key: 'isShowAll',
          className: 'pr20',
          values: [
            {
              value: '',
              name: 'My Order',
            }
          ],
        },
        {
          name: 'Channel',
          type: 'newSelect',
          key: 'channelCode',
          className: 'pr20',
          values: []
        },
        {
          name: 'Re-upload status',
          type: 'select',
          key: 'isReupload',
          className: 'pr200',
          values: [
            {
              value: '9',
              name: 'Re-upload completed',
            },
            {
              value: '1',
              name: 'Waiting for reupload',
            }
          ]
        }, {
          name: 'Filter',
          type: 'group',
          key: ['findtype', 'inputValue'],
          className: 'pr20',
          values: [{value: '', name: 'Please Select'}]
        },
        {
          name: '',
          type: 'search',
          key: '',
          className: 'pr20',
          values: []
        }
      ],
      detailDom: ''
    }
  }

  componentDidMount() {
    this.state.detailDom = $('#detailClass')
    this.getData()
  }

  currentPage(current) {
    this.setState({
      page: {
        ...this.state.page,
        currentPage: current
      }
    }, () => {
      this.getData()
    })
  }

  getData() {
    let copyState = {}
    let self = this
    self.setState({
      loading: true
    })
    for (let i in this.state.params) {
      if (this.state.params[i] != '') {
        copyState[i] = this.state.params[i]
      }
    }
    if (!copyState.startDate) {
      copyState.startDate = moment().subtract('days', 60).format('YYYY-MM-DD')
    }
    if (!copyState.endDate) {
      copyState.endDate = moment().add('days', 30).format('YYYY-MM-DD')
    }

    // isReupload 不是照片重传 0, 照片重传 1
    fetchPost(
      `${this.state.getListApi}?currentPage=${this.state.page.currentPage}&pageSize=${this.state.page.pageSize}`,
      {
        isReupload: this.state.isReupload, ...copyState,
        isNewAdd: this.state.isNewAdd,
        processNode: this.state.processNode,
        stageStatus: this.state.stageStatus
      }).then((res) => {
      if (res.code === 0) {
        const {orderList, isAuditorHeadman} = res.data
        const list = orderList

        if (isAuditorHeadman) {
          this.setState({
            loading: false,
            searchParams: {
              ...this.state.searchParams,
              list: this.state.searchParamsList0,
            },
            isAuditorHeadman,
          })
        } else {
          this.setState({
            loading: false,
            searchParams: {
              ...this.state.searchParams,
              list: this.state.searchParamsList1,
            },
            isAuditorHeadman,
          })
        }

        if (list.length > 0 && list != null) {
          this.setState({
            loading: false,
            id: list[0].auditNo,
            userId: list[0].userCode,
            tradeNo: list[0].tradeNo,
            extraStatus: list[0].extraStatus,
            photoReUploadTime: list[0].photoReUploadTime,
            photoReUploadAllow: list[0].photoReUploadAllow,
            mobileRedialAllow: list[0].mobileRedialAllow,
            page: {
              ...this.state.page,
              totalCount: res.page.totalCount || 0
            },
            item: list[0],
            activeKey: 'detail',
            isFetch: true,
            list
          })
        } else {
          self.setState({
            loading: false,
            id: null,
            userId: null,
            tradeNo: null,
            extraStatus: null,
            photoReUploadTime: null,
            photoReUploadAllow: null,
            mobileRedialAllow: null,
            item: {},
            activeKey: 'detail',
            isFetch: true,
            list: [],
            page: {
              ...this.state.page,
              totalCount: res.page.totalCount || 0
            },
          })
          message.warning('There\'s No data')
        }
      } else {
        self.setState({
          loading: false,
          id: null,
          userId: null,
          tradeNo: null,
          extraStatus: null,
          photoReUploadAllow: null,
          mobileRedialAllow: null,
          item: {},
          activeKey: 'detail',
          isFetch: true,
          list: []
        }, () => {
          message.error(res.msg)
        })
      }
      self.getAuditorWorkStat()
      self.getUserWaitTime(this.state.tradeNo)
    })
  }

  getAuditorWorkStat() {
    fetchPost(
      `/audit/user/working/stat`, {}).then((res) => {
      if (res.code === 0) {
        let auditorWorkTime = res.data
        this.setState({
          auditorWorkTime
        })
      }
    })
  }

  getUserWaitTime(tradeNo) {
    // fetchPost(
    //   `/audit/user/waitTime/get`, {
    //     tradeNo: tradeNo
    //   }).then((res) => {
    //   if (res.code === 0) {
    //     let userWaitTime = res.data
    //     this.setState({
    //       userWaitTime
    //     })
    //   }
    // })
  }

  changeParams(params) {
    let self = this
    if (params.inputValue) {
      if (params.findtype) {
        this.setState({
          params: {
            ...self.state.params,
            ...params,
            startDate: self.state.params.startDate,
            endDate: self.state.params.endDate,
          },
          isFetch: false
        }, () => {
          this.getData()
        })
      } else {
        message.warning('Please choose the Filter')
      }
    } else {
      this.setState({
        params,
        isFetch: false
      }, () => {
        this.getData()
      })
    }
  }

  chooseOrder(params) {
    let photoReUploadTime = this.state.photoReUploadTime
    let extraStatus = this.state.extraStatus
    let photoReUploadAllow = this.state.photoReUploadAllow
    let mobileRedialAllow = this.state.mobileRedialAllow
    if (params.tradeNo != null) {
      for (let i = 0; i < this.state.list.length; i++) {
        if (this.state.list[i].tradeNo === params.tradeNo) {
          photoReUploadTime = this.state.list[i].photoReUploadTime
          photoReUploadAllow = this.state.list[i].photoReUploadAllow
          mobileRedialAllow = this.state.list[i].mobileRedialAllow
          extraStatus = this.state.list[i].extraStatus
          break
        }
      }
    }
    this.setState({
      id: params.id,
      userId: params.userId,
      tradeNo: params.tradeNo,
      extraStatus: extraStatus,
      photoReUploadAllow: photoReUploadAllow,
      photoReUploadTime: photoReUploadTime,
      mobileRedialAllow: mobileRedialAllow,
      activeKey: params.activeKey,
      item: params.item,
      isFetch: false
    })

    if (params.tradeNo != null) {
      this.getUserWaitTime(params.tradeNo)
    }
  }

  changeOrder(type, id) {
    setTimeout(() => {
      this.state.list.forEach((val, index) => {
        if (val.auditNo == id) {
          this.state.list.splice(index, 1)
        }
      })
      let list = this.state.list
      if (list.length === 0) {
        this.getData()
      } else {
        this.getData()
      }
    }, 500)
  }

  showList() {
    return `${Styles.listClass} ${Styles.listRight}`
  }

  detailClass() {
    return `${Styles.detailClass} ${Styles.detailRight}`
  }

  render() {

    return (
      <div className={Styles.box}>
        <div className={Styles.headDiv}>
          {/*<span className={Styles.headSpanKey}>User Wait Time:</span>*/}
          {/*<span className={Styles.headSpanValue}>*/}
          {/*  {this.state.userWaitTime.waitTime}*/}
          {/*</span>*/}
          <span className={Styles.headSpanKey}>Total:</span>
          <span className={Styles.headSpanValue}>
            {this.state.auditorWorkTime.total}
          </span>
          <span className={Styles.headSpanKey}>Finished:</span>
          <span className={Styles.headSpanValue}>
            {this.state.auditorWorkTime.finished}
          </span>
          <span className={Styles.headSpanKey}>Waiting:</span>
          <span className={Styles.headSpanValue}>
            {this.state.auditorWorkTime.waiting}
          </span>
          <span className={Styles.headSpanKey}>AHT:</span>
          <span className={Styles.headSpanValue}>
            {this.state.auditorWorkTime.aht}
          </span>
        </div>
        <div className={SearchStyle.searchClass}>
          <Search searchParams={this.state.searchParams}
                  changeParams={(params) => this.changeParams(params)} stepType={this.state.stepType}/>
        </div>

        <Spin spinning={this.state.loading} delay={200}>
          <div className={Styles.detailWrapper}>
            <div className={this.showList()}>
              <div>
                <List
                  list={this.state.list}
                  id={this.state.id}
                  userId={this.state.userId}
                  isFetch={this.state.isFetch}
                  stepType={this.state.stepType}
                  page={this.state.page}
                  chooseOrder={(params) => this.chooseOrder(params)}
                  currentPage={(current) => this.currentPage(current)}

                />
              </div>
            </div>

            <div id='detailClass' className={this.detailClass()}>
              <Detail
                activeKey={this.state.activeKey}
                id={this.state.id}
                userId={this.state.userId}
                tradeNo={this.state.tradeNo}
                stepType={this.state.stepType}
                extraStatus={this.state.extraStatus}
                photoReUploadTime={this.state.photoReUploadTime}
                photoReUploadAllow={this.state.photoReUploadAllow}
                mobileRedialAllow={this.state.mobileRedialAllow}
                item={this.state.item}
                processNode={this.state.processNode}
                changeOrder={(type, id) => this.changeOrder(type, id)}/>
            </div>
          </div>
        </Spin>

      </div>
    )
  }
}

export default Index
